const express = require("express");
const app = express();
const http = require("http");
const server = http.createServer(app);
const { Server } = require("socket.io");
const cors = require("cors");
const router = require("./router");
const jwt = require("jsonwebtoken");
const { User } = require("./models");

const io = new Server(server, {
  cors: {
    // origin: "http://192.168.29.143:8080/",
    origin: "*",
  },
});

// 配置解析请求体中间件，他会把解析到的数据挂载到 req.body 上
app.use(express.json());
// 配置跨域中间件
app.use(cors());
// 注册路由
app.use("/api", router);
// 处理 http 协议使用 express 的实例 app
/* app.get("/", (req, res) => {
  res.sendFile(__dirname + "/index.html");
}); */

// const clients = [];

// 处理 websocket 协议使用 socket.io 的实例 io
// 连接只会触发一次，所以需要在 io.on('connection',...) 里处理客户端的连接

// socket中间件
io.use((socket, next) => {
  const token = socket.handshake.auth.token;
  jwt.verify(
    token,
    "a053e3a3-a00d-4c1f-b4bb-fd71e3aab361",
    async (err, decoded) => {
      if (err) {
        return next(new Error("身份验证失败"));
      }
      const user = await User.findById(decoded.userId);
      console.log("🚀 ~ user:", user);
      if (!user) {
        return next(new Error("用户不存在"));
      }
      socket.request.user = user;
      next();
    }
  );
});

io.on("connection", (socket) => {
  // clients.push(socket);
  // console.log("a user connected", clients.length);
  // 接发消息：socket.on(‘消息类型’, 回调)
  // 发送消息：socket.emit('发送消息', 数据)
  socket.on("chat message", (data) => {
    console.log("chat message:", data);
    socket.emit("chat message", {
      nickname: socket.request.user.username,
      message: data,
    });

    /* clients.forEach((client) => {
      client.emit("chat message", "群发的消息");
    }); */

    // 群发消息
    // io.emit("chat message", "群发的消息");
    // 发给不包括当前发送消息的socket其他用户
    // socket.broadcast.emit(
    //   "chat message",
    //   "发给不包括当前发送消息的socket其他用户"
    // );
  });

  socket.on("disconnect", () => {
    console.log("客户端断开连接");
    /* const index = clients.findIndex((client) => client === socket);
    if (index !== -1) {
      clients.splice(index, 1);
    } */
  });
});

server.listen(3000, () => {
  console.log("listening on *:3000");
});
